package com.bianmaba.netty.common.encoder;


import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.function.Supplier;

public class LengthFieldFrameEncoder {
    private byte[] data;
    private int headLength;
    private int dataLength;

    public LengthFieldFrameEncoder(String message, Charset chartset, int headLength) {
        this.data = message.getBytes(chartset);
        this.headLength = headLength;
        this.dataLength = data.length;
    }

    public LengthFieldFrameEncoder(String message, int headLength) {
        this(message, Charset.defaultCharset(), headLength);
    }

    public LengthFieldFrameEncoder(byte[] data, int headLength) {
        this.data = data;
        this.headLength = headLength;
        this.dataLength = data.length;
    }

    private byte[] initBytes() {
        return ByteBuffer.allocate(headLength).putInt(dataLength).array();
    }

    public byte[] encode() {
        byte[] headBytes = initBytes();
        byte[] combined = new byte[headBytes.length + this.data.length];
        System.arraycopy(headBytes, 0, combined, 0, headBytes.length);
        System.arraycopy(this.data, 0, combined, headBytes.length, this.data.length);
        return combined;
    }
}
